package fr.mywiki.view.web.struts.action.structure;

import java.io.IOException;
import java.util.HashMap;

import javax.ejb.FinderException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import fr.mywiki.business.log.LogManager;
import fr.mywiki.business.structure.StructureLite;
import fr.mywiki.business.structure.TreeManager;
import fr.mywiki.business.xml.AJAXManager;
import fr.mywiki.model.ejbAdapter.DataController;
import fr.mywiki.view.web.struts.form.structure.TreeStructureForm;

/**
 * Dispatch action class for the tree structure manipulation.
 */
public class TreeStructureAction extends DispatchAction {
	public static final boolean verbose = AJAXManager.verbose;
	
	/** Action called when the user clicks on a structure element by clicking on it */
	public ActionForward selectAjax(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		TreeStructureForm treeForm = (TreeStructureForm) actionForm;

		Long id = new Long(request.getParameter("structureId"));
		if(verbose)
			LogManager.println("Received from client : selectAjax on " + id.toString());

		treeForm.getSelectStructureController().setIdStructure(id);
		treeForm.getSelectStructureController().setStructure((StructureLite) DataController.getValue(id,
				StructureLite.TYPE_ENT));
		
		AJAXManager.sendResponse(AJAXManager.XML_CONTENT_TYPE, buildElementMap(
				treeForm.getSelectStructureController().getStructure(), request), new HashMap(), response);

		return null;
	}

	public ActionForward selectRootAjax(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws FinderException, IOException {
		TreeStructureForm form = (TreeStructureForm) actionForm;
		
		if(verbose)
			LogManager.println("Received from client : selectAjaxRoot");

		form.getSelectStructureController().setIdStructure(null);
		form.getSelectStructureController().setStructure(null);
		form.getSelectStructureController().setExpandJS(TreeManager.getExpandCodeJS(null));

		AJAXManager.sendResponse(AJAXManager.XML_CONTENT_TYPE, buildElementMap(
				null, request), new HashMap(), response);

		return null;
	}
	
	protected HashMap buildElementMap(StructureLite structure, HttpServletRequest request) {
		return new HashMap();
	}
}
